---
title: "Core Syntax and Structure Comparison"
description: "Learn the basic syntax of Rust from a JavaScript perspective, including variable declaration, data types, control flow, and function definitions."
---

# Core Syntax and Structure Comparison

## 📖 Learning Objectives

By comparing the basic syntax of JavaScript and Rust, you will quickly grasp the core concepts of Rust. We will start with the JavaScript syntax you are familiar with and gradually introduce Rust's syntax features.

---

## 🎯 Variable Declaration and Scope

### JavaScript Variable Declaration

In JavaScript, we use `var`, `let`, and `const` to declare variables:

<UniversalEditor title="JavaScript Variable Declaration" compare={true}>
```javascript !! js
// JavaScript variable declaration
var oldWay = "Not recommended";
let mutableVar = "Can be reassigned";
const immutableVar = "Cannot be reassigned";

// Variables can be reassigned
mutableVar = "New value";
console.log(mutableVar); // Outputs: New value

// Variables declared with const cannot be reassigned
// immutableVar = "Trying to modify"; // This will throw an error
```
</UniversalEditor>

### Rust Variable Declaration

Rust uses the `let` keyword to declare variables, which are immutable by default:

<UniversalEditor title="Rust Variable Declaration" compare={true}>
```rust !! rs
// Rust variable declaration
let immutable_var = "Immutable by default";
let mut mutable_var = "Can be reassigned"; // Requires the mut keyword

// Mutable variables can be reassigned
mutable_var = "New value";
println!("{}", mutable_var); // Outputs: New value

// Immutable variables cannot be reassigned
// immutable_var = "Trying to modify"; // Compile error!

// Variable shadowing - a concept unique to Rust
let x = 5;
let x = x + 1; // Creates a new variable x, shadowing the old one
println!("x = {}", x); // Outputs: x = 6
```
</UniversalEditor>

### Key Differences

1.  **Default Immutability**: Variables in Rust are immutable by default and require the `mut` keyword to be modified.
2.  **Variable Shadowing**: Rust allows redeclaring a variable with the same name in the same scope.
3.  **Type Inference**: The Rust compiler can automatically infer the variable type.

---

## 📊 Basic Data Type Comparison

### JavaScript Data Types

JavaScript is a dynamically typed language:

<UniversalEditor title="JavaScript Data Types" compare={true}>
```javascript !! js
// JavaScript primitive data types
let number = 42;           // Number
let string = "Hello";      // String
let boolean = true;        // Boolean
let array = [1, 2, 3];     // Array
let object = {name: "Rust"}; // Object
let nullValue = null;      // null
let undefinedValue;        // undefined

// Type checking
console.log(typeof number);        // "number"
console.log(typeof string);        // "string"
console.log(typeof boolean);       // "boolean"
console.log(Array.isArray(array)); // true
```
</UniversalEditor>

### Rust Data Types

Rust is a statically typed language, and types are determined at compile time:

<UniversalEditor title="Rust Data Types" compare={true}>
```rust !! rs
// Rust primitive data types
let integer: i32 = 42;           // 32-bit signed integer
let unsigned: u32 = 42;          // 32-bit unsigned integer
let float: f64 = 3.14;           // 64-bit floating-point number
let boolean: bool = true;        // Boolean value
let character: char = 'A';       // Unicode character
let string: String = String::from("Hello"); // String
let string_slice: &str = "World"; // String slice

// Array - fixed length
let array: [i32; 5] = [1, 2, 3, 4, 5];

// Tuple - can contain different types
let tuple: (i32, f64, &str) = (500, 6.4, "hello");

// Accessing array and tuple elements
println!("First element of the array: {}", array[0]);
println!("First element of the tuple: {}", tuple.0);
```
</UniversalEditor>

### Type System Differences

1.  **Static vs. Dynamic**: Rust checks types at compile time, while JavaScript checks at runtime.
2.  **Integer Types**: Rust has multiple integer types (i8, i16, i32, i64, u8, u16, u32, u64).
3.  **Strings**: Rust distinguishes between `String` (owned) and `&str` (borrowed).

---

## 🔄 Control Flow Comparison

### JavaScript Control Flow

<UniversalEditor title="JavaScript Control Flow" compare={true}>
```javascript !! js
// JavaScript conditional statements
let age = 18;

if (age >= 18) {
    console.log("Adult");
} else if (age >= 12) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// switch statement
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("It's Monday");
        break;
    case "Tuesday":
        console.log("It's Tuesday");
        break;
    default:
        console.log("Some other day");
}

// Loops
for (let i = 0; i < 5; i++) {
    console.log(i);
}

let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
    console.log(num);
}
```
</UniversalEditor>

### Rust Control Flow

<UniversalEditor title="Rust Control Flow" compare={true}>
```rust !! rs
// Rust conditional statements
let age = 18;

if age >= 18 {
    println!("Adult");
} else if age >= 12 {
    println!("Teenager");
} else {
    println!("Child");
}

// 'if' is an expression and can be used in assignments
let status = if age >= 18 { "Adult" } else { "Minor" };
println!("Status: {}", status);

// 'match' statement (like switch, but more powerful)
let day = "Monday";
match day {
    "Monday" => println!("It's Monday"),
    "Tuesday" => println!("It's Tuesday"),
    _ => println!("Some other day"), // _ is a wildcard
}

// Loops
for i in 0..5 {
    println!("{}", i);
}

let numbers = vec![1, 2, 3, 4, 5];
for num in &numbers {
    println!("{}", num);
}

// while loop
let mut count = 0;
while count < 5 {
    println!("count: {}", count);
    count += 1;
}

// loop (infinite loop)
let mut counter = 0;
loop {
    counter += 1;
    if counter > 5 {
        break; // Exit the loop
    }
    println!("counter: {}", counter);
}
```
</UniversalEditor>

### Control Flow Differences

1.  **`if` Expression**: Rust's `if` can return a value, making it useful for assignments.
2.  **`match` Statement**: More powerful than JavaScript's `switch`, supporting pattern matching.
3.  **Loop Syntax**: Rust uses a concise `for in` syntax.

---

## 🏗️ Function Definition Comparison

### JavaScript Functions

<UniversalEditor title="JavaScript Function Definition" compare={true}>
```javascript !! js
// JavaScript function definition
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrow function
const greetArrow = (name) => {
    return `Hello, ${name}!`;
};

// Simplified arrow function
const greetSimple = (name) => `Hello, ${name}!`;

console.log(greet("World"));
console.log(greetArrow("World"));
console.log(greetSimple("World"));
```
</UniversalEditor>

### Rust Functions

<UniversalEditor title="Rust Function Definition" compare={true}>
```rust !! rs
// Rust function definition
// Parameter types and return type must be specified
fn greet(name: &str) -> String {
    // No 'return' keyword needed for the last expression
    format!("Hello, {}!", name)
}

// Another function
fn add(a: i32, b: i32) -> i32 {
    a + b // This is an expression, so it returns the value
}

fn main() {
    println!("{}", greet("World"));
    println!("1 + 2 = {}", add(1, 2));
}
```
</UniversalEditor>

### Function Differences

1.  **Type Annotations**: Rust requires explicit type annotations for function parameters and return values.
2.  **Return Values**: In Rust, the last expression in a function is automatically returned (no `return` keyword needed, semicolon omitted).
3.  **Arrow Functions**: Rust does not have an equivalent to JavaScript's arrow functions, but closures serve a similar purpose.

---

## 📚 Summary

In this module, we compared the core syntax of JavaScript and Rust. You should now have a basic understanding of:
- How to declare variables and their immutability in Rust.
- The differences in basic data types.
- The powerful control flow structures in Rust like `match` and `if` expressions.
- The syntax for defining functions with explicit types.

Next, we will explore the module systems of both languages. 